module lpuart_de(
input uart_clk,
input uart_rst_n,

input [19:0] brr_dat,

input       dem,
input [4:0] dedt,
input [4:0] deat,
input  stop_bit ,//uart stop bit pulse
output de_o , //de pad output 
input  start_pre , // assertion trans begin pulse
output start //start bit begin pulse 
);

reg [4:0] deat_cnt ; 
reg start_d ;
reg de_neg_d ;
reg [4:0] dedt_cnt ;
reg [9:0] pre_cnt ;
reg de_o ;

wire de_neg ;
wire de_neg_e ;
wire [9:0] rs485_p = brr_dat[19:0] ; 
wire start_e ;

always@(posedge uart_clk or negedge uart_rst_n)begin
if(!uart_rst_n)
          de_o <= 1'b0 ;
else if(dem & tx_start)
          de_o <= 1'b1 ;
else if (dem & de_neg)
          de_o <= 1'b0 ;
end

assign empty_p  = (rs_485[9:0] == 10'h0) ;

always@(posedge uart_clk or negedge uart_rst_n)begin
if(!uart_rst_n)
           pre_cnt [9:0] <= 10'h0 ;
else if(dem & start_pre)
           pre_cnt [9:0] <= 10'h0 ;
else if(dem & stop_bit)
           pre_cnt [9:0] <= 10'h0 ;
else if(dem & empty_p)
           pre_cnt [9:0] <= 10'h3ff ;
else if(dem & !empty_p)
           pre_cnt [9:0] <= pre_cnt[9:0] + 10'h1 ;
end

assign start_e  = (deat_cnt == deat) ;

always@(posedge uart_clk or negedge uart_rst_n)begin
if(!uart_rst_n)begin
       start_d  <=  1'b0 ;
       de_neg_d <=  1'b0 ;
end else begin 
       start_d  <=  start_e ;
       de_neg_d <=  de_neg_e ;
end

assign start    = start_e & ~start_d ;
 

always@(posedge uart_clk or negedge uart_rst_n)begin
if(!uart_rst_n)
           deat_cnt      <= 5'h0 ;
else if(start_pre)
           deat_cnt      <= 5'h0 ;
else if((deat_cnt != deat) & (pre_cnt==10'h3ff))
           deat_cnt      <= deat_cnt + 5'h1 ;
end
always@(posedge uart_clk or negedge uart_rst_n)begin
if(!uart_rst_n)
           dedt_cnt      <= 5'h0 ;
else if(stop_bit)
           dedt_cnt      <= 5'h0 ;
else if((dedt_cnt != dedt) & (pre_cnt==10'h3ff))
           dedt_cnt      <= dedt_cnt + 5'h1 ;
end
assign de_neg_e = dedt_cnt == dedt ;
assign de_neg   = de_neg_e & ~de_neg_d ;

